import React, { Component, Fragment } from 'react';
import { Spin, Card, Row, Col, Form, Input, Select, DatePicker, Button, Rate, Badge, Modal, Pagination, Popconfirm, message, List } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import ReplyModal from './ReplyModal';
import HeaderTab from '@/components/HeaderTab';
import pathToRegexp from 'path-to-regexp';

const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
@Form.create()

class Rates extends React.Component {
  state = {
    previewVisible1: false,
    previewVisible2: false,
    modaltitle: "",
    imgUrl: "",
    loadSearch: false,
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
      pageIndex: 1,
    },
    tabs: [
      {
        title: '全部评价',
        key: `/${window.storeId}/order/rates`,
        // disabled: true
      },
      {
        title: '待审核',
        key: `/${window.storeId}/order/rates/pending`,
      }
    ],
  };
  componentDidMount() {
    this.init();
    window.Isoption = true;
  }

  componentWillMount() {
    window.Isoption = false;
  }

  // 头部标签页切换
  onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };
  init = () => {
    const { dispatch, match } = this.props;

    const { paginationProps } = this.state;
    dispatch({
      type: 'orderRates/GetEvaluateListWithPage',
      params: {
        PageIndex: paginationProps.pageIndex,
        PageSize: paginationProps.pageSize,
        Status: pathToRegexp('/:storeId/order/rates').exec(match.url) ? -1 : 0
      },
      callBack: {
        success: (data) => {
          this.setState({ paginationProps: { ...this.state.paginationProps, total: data.Total } })
        }, error: (data) => {

          message.error('获取评价列表失败')

        }
      }
    })
  }

  handleCancel = () => this.setState({
    previewVisible1: false,
    previewVisible2: false,
    modaltitle: "",
  })
  handleSearch = () => {
    const { paginationProps } = this.state
    let pagination = {
      ...paginationProps,
      pageIndex: 1,
      pageSize: 10
    };
    this.setState({
      paginationProps: pagination,
    }, () => {
      this.handleSubmit();
    })
  }
  handleSubmit = () => {
    let { dispatch, match } = this.props;

    const { paginationProps } = this.state
    this.props.form.validateFields((err, values) => {
      this.setState({ loadSearch: true })
      let param = {
        PageIndex: paginationProps.pageIndex,
        PageSize: paginationProps.pageSize,
        Status: pathToRegexp('/:storeId/order/rates').exec(match.url) ? -1 : 0
      }
      if (values.ScoreLevel) {
        param = { ...param, ScoreLevel: values.ScoreLevel }
      }
      if (values.OrderNo) {
        param = { ...param, OrderNo: values.OrderNo }
      }
      if (values.Type) {
        param = { ...param, ScoreLevel: values.Type }
      }
      if (values.Time) {
        param = {
          ...param,
          StartDate: values.Time[0].format('YYYY-MM-DD HH:mm:ss'),
          EndDate: values.Time[1].format('YYYY-MM-DD HH:mm:ss'),
        }
      }

      if (values.ProductName) {
        param = { ...param, ProductName: values.ProductName }
      }
      if (values.MemberName) {
        param = { ...param, MemberName: values.MemberName }
      }
      dispatch({
        type: 'orderRates/GetEvaluateListWithPage',
        params: param,
        callBack: {
          success: (data) => {
            this.setState({ paginationProps: { ...this.state.paginationProps, total: data.Total }, loadSearch: false })
          }, error: (data) => {
            console.log(data)
            message.error('获取评价列表失败')

          }
        }
      })
    })
  }
  showmodal = (imgUrl) => this.setState({
    previewVisible2: true,
    imgUrl
  })
  showmodalhuifu = (item) => this.setState({
    previewVisible1: true,

    modaltitle: `回复${item.MemberName}`,
  })
  reset = () => {
    const { form } = this.props;
    form.resetFields();
  }

  renderForm = () => {
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldsValue
    } = this.props.form;
    const { loadSearch } = this.state
    return (
      <Form layout="inline">
        <Row>
          <Col span={8}>
            <FormItem label="订单号：">
              {getFieldDecorator('OrderNo', {
              })(
                <Input placeholder="" style={{ width: '100%' }} />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="评价星级：">
              {getFieldDecorator('ScoreLevel', {
              })(
                <Select className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>一星</Option>
                  <Option value={2}>二星</Option>
                  <Option value={3}>三星</Option>
                  <Option value={4}>四星</Option>
                  <Option value={5}>五星</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="评价方式：">
              {getFieldDecorator('Type', {
              })(
                <Select className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>默认好评</Option>
                  <Option value={2}>用户自评</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label="评价时间：">
              {getFieldDecorator('Time', {
              })(
                <RangePicker
                  style={{ width: '100%' }}
                  showTime
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始日期', '    结束日期']}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="商品名称：">
              {getFieldDecorator('ProductName', {
              })(
                <Input placeholder="" style={{ width: '100%' }} />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="买家：">
              {getFieldDecorator('MemberName', {
              })(
                <Input placeholder="" style={{ width: '100%' }} />
              )}
            </FormItem>

          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div className="screenNavButton">
            <Button
              type="primary"
              onClick={this.handleSearch}
              loading={loadSearch}
            >
              筛选
           </Button>
            <Button

              style={{ marginLeft: 8 }}
              onClick={this.reset}
            >
              重置
            </Button>

          </div>
        </div>
      </Form>
    )
  }
  huifu = () => {
    return (
      <Row>
        <Col span={5}>回复内容：</Col>
        <Col span={16}><TextArea rows={4} maxLength={50} /></Col>
      </Row>
    )
  }
  noPass = (rid) => {
    const { dispatch } = this.props;
    dispatch({
      type: `orderRates/AuditEvaluateToNoPass`,
      params: { Id: rid, p: Math.random() },
      callBack: {
        success: (data) => {
          message.success("拒审成功！")
          this.init()
        }, error: (data) => {
          console.log(data)
          message.error("拒审失败！")
        }
      }
    });

  }

  pass = (rid) => {
    const { dispatch } = this.props;
    dispatch({
      type: `orderRates/AuditEvaluateToPass`,
      params: { Id: rid, p: Math.random() },
      callBack: {
        success: (data) => {
          message.success("审核成功！")
          this.init()
        }, error: (data) => {
          console.log(data)
          message.error("审核失败！")
        }
      }
    });
  }
  onChangePage = (current, pageSize) => {
    let { paginationProps } = this.state;
    let pagination = {
      ...paginationProps,
      pageIndex: current,
      pageSize: pageSize
    };
    this.setState({
      paginationProps: pagination,
    }, () => {
      this.handleSubmit();
    })
  }
  render() {
    const { previewVisible1, previewVisible2, modaltitle, paginationProps } = this.state;

    const { evaluateList, loading, loadSearch,oemInfo } = this.props

    return (
      <Fragment>
        {/* <HeaderTab
          _this={this}
          type="slider"
          onChange={this.onTabChange}
          tabs={this.state.tabs}
        >
        </HeaderTab> */}

        <Card bordered={false}>
          <div style={{ background: '#fafafa', marginBottom: 16, paddingTop: 16, paddingRight: 16, boxSizing: 'border-box' }}>
            <div className="tableListForm">{this.renderForm()}</div>
          </div>
          <Row className={styles.RatesTitle}>
            <Col span={4}>评价星级/服务评价</Col>
            <Col span={8}>评价内容</Col>
            <Col span={2}>买家</Col>
            <Col span={5}>商品信息</Col>
            <Col span={3}>审核状态</Col>
            <Col span={2}>操作</Col>
          </Row>
          <Spin spinning={loading}>
            {/* 列表开始 */}
            <List
              itemLayout="vertical"
              size="large"
              dataSource={evaluateList.DataList && evaluateList.DataList ? evaluateList.DataList : []}
              renderItem={item => (
                <List.Item>

                  <Fragment>
                    <Row type="flex" justify="space-between" className={styles.RatesOrder}>
                      <Col span={6}>{item.OrderNo}</Col>
                      <Col span={6}>评价时间：{item.CreateTime}</Col>
                    </Row>
                    <Row className={styles.RatesList}>
                      <Col span={4}>
                        <Rate value={item.ScoreLevel} disabled={true} /><br />
                        商家服务：{item.ServiceScore}分<br />
                        发货物流：{item.LogisticsScore}分<br />
                        宝贝描述：{item.BabyScore}分
                </Col>
                      <Col span={8}>
                        {item.Content ? item.Content : "此用户未填写评价内容"}<br />
                        {
                          item.ImageList && item.ImageList.map((item) => {

                             return <img src={`${oemInfo.cdnUrl}/${item}?x-oss-process=style/c_134`} onClick={() => this.showmodal(`${oemInfo.cdnUrl}/${item}`)} />
                          })
                        }

                      </Col>
                      <Col span={2}>{item.MemberName}</Col>
                      <Col span={5}>
                        <a className="xkd-text-ellipsis-2">{item.ProductName}</a>
                        <span>{item.SkuName}</span>
                      </Col>
                      <Col span={3}>
                        {
                          item.AuditStatus === 0 || item.AuditStatus === 2 ? <Badge status="error" /> : <Badge status="success" />
                        }
                        {item.AuditStatusName}
                      </Col>
                      <Col span={2}>

                        {
                          item.AuditStatus === 0 ?
                            <Popconfirm title="是否通过审核？" onConfirm={() => this.pass(item.Id)} onCancel={() => this.noPass(item.Id)} okText="通过" cancelText="拒绝">
                              <a >审核</a>
                            </Popconfirm>
                            : null
                        }
                        {
                          item.ReplyContent ? null :
                            <a onClick={() => {
                              const title = `回复${item.MemberName}`;

                              this.ReplyModal.show({ title, Id: item.Id }, this.init)
                            }}>回复</a>
                        }

                      </Col>
                    </Row>
                  </Fragment>

                </List.Item>
              )}
            />

          </Spin>

          <Pagination
            showSizeChanger
            total={paginationProps.total}
            current={paginationProps.pageIndex}
            pageSize={paginationProps.pageSize}
            onChange={this.onChangePage}
            className={styles.Pag}
          />
        </Card>
        <Modal
          visible={previewVisible2}
          footer={null}
          onCancel={this.handleCancel}
          width={640}
          centered
          className={styles.Modal}
        >
          <img style={{ width: '100%' }} src={this.state.imgUrl} />
        </Modal>
        <ReplyModal
          ref={e => {
            this.ReplyModal = e;
          }}
        />



      </Fragment>
    );
  }
}

export default connect(({ orderRates, global, loading }) => ({
  evaluateList: orderRates.evaluateList,
  oemInfo: global.oemInfo,
  loading: loading.effects['orderRates/GetEvaluateListWithPage'],

  loadReply: loading.effects['orderRates/Reply'],
  loadAuitNoPass: loading.effects['orderRates/AuditEvaluateToNoPass'],
  loadAuitPass: loading.effects['orderRates/AuditEvaluateToPass'],
}))(Rates)
